import axios, {
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
  type AxiosRequestConfig,
} from "axios";
import { useTokenStore } from "@/store";
const instance = axios.create({
  baseURL: "/api",
  timeout: 1500,
});
const store = useTokenStore();
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers["token"] = store.token;
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);
instance.interceptors.response.use(
  (res: AxiosResponse) => {
    return res;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);
function request<T = any>(config: AxiosRequestConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    instance
      .request(config)
      .then((res: AxiosResponse) => {
        resolve(res.data);
      })
      .catch((err: AxiosError) => {
        reject(err);
      });
  });
}
export async function get<T = any>(config: AxiosRequestConfig): Promise<T> {
  return request({ ...config, method: "GET" });
}
export async function post<T = any>(config: AxiosRequestConfig): Promise<T> {
  return request({ ...config, method: "POST" });
}
export async function put<T = any>(config: AxiosRequestConfig): Promise<T> {
  return request({ ...config, method: "PUT" });
}
export async function deleted<T = any>(config: AxiosRequestConfig): Promise<T> {
  return request({ ...config, method: "DELETE" });
}
export default instance;
